require "Common/define"
require "Logic/Config"
require "Common/functions"
require "View/CharactorUI/UIBreakStone"

UIDrawAnimation = {};
HelperFunc.SetUIEnv(UIDrawAnimation)
local this = UIDrawAnimation;

this.gameObject = nil;
this.transform = nil;
this.LuaBehaviour = nil;

this.eff_rock = nil;
this.eff_bluerock = nil;
this.rawImage = nil;

this.heroPanel = nil;
this.heroBG = nil;
this.btnHero = nil;
this.heroLihui = nil;
this.objDraw = nil;
this.heroElement = nil;
this.heroQuality = nil;
this.btnSkip = nil;
this.heroname = nil;
this.num = nil;
this.skipController = nil;
this.drawWrapper = nil;
this.drawWrapper2 = nil;
this.drawAnimation = nil;
this.drawAnim = nil;
this.starNum = nil;
this.heroController = nil;
this.hasInit = false;
this.callbackFun = nil;
this.callbackSkip = nil;
this.effCoroutine = nil;
this.skipBgBtn = nil;
this.heroId = nil;
this.hasHeroIds = nil;
this.bSkip = false;
this.heroConfig = nil;
this.qualityFrame = nil
this.qualityIcon = nil
this.qualityNumIcon = nil
this.staegeController = nil
this.maxController = nil
this.procession = nil;
this.newIcon = nil;
this.idleTimer = nil;
this.onlyShowHeroInfo = nil;
this.trick = nil
this.special = nil
this.specialTwo = nil
this.passive = nil
this.trickGroup = {};
this.specialGroup={};
this.specialTwoGroup ={};
this.passiveGroup = {};
this.skill5Group = {}
this.newTra = nil
this.level = nil
this.btnAward = nil
this.btninfo = nil
this.currentHeroData = nil
this.tab_qualitybg = {"bg_blue", "bg_purple", "bg_yellow"};
this.elementName ={"element_1","element_2","element_3","element_4","element_5"}
this.colorObj = Color.New(1, 1, 1, 1)
this.curAlpha = 0;
this.updateTimer = nil

function UIDrawAnimation.Init(Id, heroIds, skip, callback, skipFun, isOnlyShowHeroInfo, notShowNew)
    if type(Id) == "table" then
        heroId = Id[1];
        this.showHeroStar = Id[2]
    else
        heroId = Id;
        this.showHeroStar = nil;
    end
    hasHeroIds = heroIds;
    bSkip = skip;
    callbackFun = callback;
    callbackSkip = skipFun;
    onlyShowHeroInfo = isOnlyShowHeroInfo;
    this.notShowNew = notShowNew;

    local name, packageName = getUIName(PanelNames.UIDrawAnimation);
    panelMgr:ShowUI(name, packageName, this.onCreate,Config.useLocalUI);
end

function UIDrawAnimation.onCreate(obj)
    gameObject = obj;

    this.colorObj = Color.New(1, 1, 1, 1)
    this.curAlpha = 0;
    
    this.isNeedRemovePackage = false
    if not hasInit then
        hasInit = true;
        starNum = obj:GetChild("starNum");
        skipController = obj:GetController("showSkip")
        heroController = obj:GetController("showHero")
        skipBgBtn = obj:GetChild("skipBg"); -- 天使界面的跳过背景
        btnHero = obj:GetChild("BG"); -- 立绘界面的跳过背景
        heroLihui = obj:GetChild("herolihui")
        btnSkip = obj:GetChild("btnSkip"); -- 翻书界面的一键跳过
        heroname = obj:GetChild("heroname")
        drawAnim = obj:GetChild("drawAnimation")
        this.spineBookObj = obj:GetChild("spineBook");
        this.spineBook = this.spineBookObj.wrapTarget;
        this.spineCardObj = obj:GetChild("spineCard");
        this.spineCard = this.spineCardObj.wrapTarget;

        local quality = obj:GetChild("heroquality")
        qualityFrame = quality:GetChild("frame")
        qualityIcon = quality:GetChild("icon")
        qualityNumIcon = quality:GetChild("numIcon")
        staegeController = quality:GetController("jinjie")
        maxController = quality:GetController("LR");
        breakStone = UIBreakStone:new(quality);
        this.fade = obj:GetTransition("fade");
        trick= obj:GetChild("skill1")
        special = obj:GetChild("skill2")
        specialTwo = obj:GetChild("skill3")
        passive = obj:GetChild("skill4")
        skill5 = obj:GetChild("skill5")
        newTra = obj:GetTransition("new")
        btnAward = obj:GetChild("btn_award")
        btninfo = obj:GetChild("archivesBtn")

        procession = obj:GetChild("icon")
        newIcon = obj:GetChild("n35")
        this.HeroLineTextController = obj:GetController("say")
        this.Txt_ActorLines = obj:GetChild("Txt_ActorLines")
        this.showIconController = obj:GetController("showIcon")
        this.ctrlSkillRace = obj:GetController("race")
        this.ctrlSkillFifth = obj:GetController("fifthSkill")
        --drawWrapper = GoWrapper.New()
        drawWrapper2 = GoWrapper.New()
        this.addEvent();
        this.resetEffect();
    end
    this.clearEffect();
    heroController.selectedIndex = 0;
    if onlyShowHeroInfo then
        this.resetEffect();
        effCoroutine = coroutine.start(this.refreshHero);
    else
        effCoroutine = coroutine.start(this.showEffect);
        if logicMgr.HeroManager.drawNeedShowItems ~= nil then
            this.onClickHero();
        end
    end
end

function UIDrawAnimation.addEvent()
    skipBgBtn.onClick:Add(this.onClickHero);
    btnHero.onClick:Add(this.onClickHero);
    btnSkip.onClick:Add(this.onClickSkip);
    trick.onClick:Add(this.onClickShowTrickSkill)
    special.onClick:Add(this.onClickShowSpecialSkill)
    specialTwo.onClick:Add(this.onClickShowSpecialTwoSkill)
    passive.onClick:Add(this.onClickShowPassiveSkill)
    skill5.onClick:Add(this.onClickSkill5)
    btnAward.onClick:Add(this.GetWard)
    btninfo.onClick:Add(this.Info)
end

function UIDrawAnimation.removeEvent()
    skipBgBtn.onClick:Remove(this.onClickHero);
    btnHero.onClick:Remove(this.onClickHero);
    btnSkip.onClick:Remove(this.onClickSkip);
    trick.onClick:Remove(this.onClickShowTrickSkill)
    special.onClick:Remove(this.onClickShowSpecialSkill)
    specialTwo.onClick:Remove(this.onClickShowSpecialTwoSkill)
    passive.onClick:Remove(this.onClickShowPassiveSkill)
    skill5.onClick:Clear()
    btnAward.onClick:Remove(this.GetWard)
    btninfo.onClick:Remove(this.Info)
end

function UIDrawAnimation.GetWard()
    local data = logicMgr.HeroManager.getHandbookByModelId(currentHeroData.partnerModelId,true);
    if data ~= nil and not data.isReward then
        partnerHandler.sendHandbookReward(currentHeroData.partnerModelId);
    end
    btnAward.visible = false
end

function UIDrawAnimation.Info()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HeroArchive, true,btninfo) then
        showUI(PanelNames.UICharactorInfoArchives, currentHeroData);
    end
end

function UIDrawAnimation.OnDestroy()
    utimer.remove(this.updateTimer)
    this.updateTimer = nil
    if hasInit == true then
        hasInit = false;
        this.removeEvent();
    end
    if this.isNeedRemovePackage and UIPackage.GetById("FUI/CharactorUI") then
        UIPackage.RemovePackage("FUI/CharactorUI")
    end
    breakStone:destroy();
    if objDraw ~= nil then
        local name = objDraw.name
        destroyImmediate(objDraw)
        objDraw = nil
        HelperFunc.UnloadSingleLihui(name)
    end

    if drawWrapper then
        drawWrapper:Dispose()
        drawWrapper = nil
    end

    if drawWrapper2 then
        drawWrapper2:Dispose()
        drawWrapper2 = nil
    end

    if callbackFun ~= nil then
        local ccc = callbackFun;
        callbackFun = nil
        ccc();
    end
end

function UIDrawAnimation.OnEnable()
end

function UIDrawAnimation.OnDisable()
    AudioManager.TryStopLoopSound()
end

function UIDrawAnimation.resetEffect()
    drawAnim.visible = false;
    skipController.selectedIndex = 0;
end

function UIDrawAnimation.clearEffect()
    if drawAnimation~=nil then
        destroy(drawAnimation);
        drawAnimation = nil;
    end
    if objDraw~=nil then
        local name = objDraw.name
        destroyImmediate(objDraw)
        objDraw = nil
        HelperFunc.UnloadSingleLihui(name)
    end
    if idleTimer~=nil then
        idleTimer:Stop();
    end
end

function UIDrawAnimation.showEffect()
    newIcon.visible = false;
    heroController.selectedIndex = 0
    skipController.selectedIndex = 1
    this.spineBookObj.visible = true;
    this.spineCardObj.visible = false;
    Util.PlayAction(this.spineBook, "idle", true);
    --抽卡动画-书放置
    AudioManager.Play(4001)
    this.spineBooking = 2;
end

function UIDrawAnimation.refreshHero()
    if not UIPackage.GetById("FUI/CharactorUI") then
        this.isNeedRemovePackage = true;
        AddUIPackageDepend(PanelNames.UIDrawAnimation, "FUI/CharactorUI")
    end
    this.clearEffect();
    newIcon.visible = true;
    this.isDrawing = false;
    this.spineBookObj.visible = false;
    this.spineCardObj.visible = false;
    heroController.selectedIndex = 1;
    newTra:Play()
    btnSkip.visible = (bSkip);
    this.showIconController.selectedIndex = this.notShowNew and 1 or 0;
    this.spineBooking = 1;
    heroConfig = G.dataTable["t_hero"][tostring(heroId)];
    if heroConfig == nil then
        printError("heroConfig is nil, t_hero heroId==", heroId)
    end
    currentHeroData = logicMgr.HeroManager.getHeroDatabyModelId(heroId,true)
    local data = logicMgr.HeroManager.getHandbookByModelId(currentHeroData.partnerModelId,true);
    btnAward.visible = data ~= nil and not data.isReward;
    if data and not data.isReward then
        local heroData = HeroManager.getHeroDatabyModelId(currentHeroData.partnerModelId,true)
        if heroData then
            btnAward.title = string.format(getLanguage("HeroHello001"), heroData.name)
        end
    end
    this.level =logicMgr.HeroManager.getHeroShowLevelByPartnerId(currentHeroData.partnerId)
    this.refresh()
    
    if heroConfig then
        heroname.text = getLanguage(heroConfig.f_HeroName);
        local drawing = logicMgr.HeroManager.GetHeroDrawingPath(heroId)
        resMgr:LoadModelPrefab(drawing,function (go)
            if idleTimer~=nil then
                idleTimer:Stop();
            end
            this.isDrawing = true;
            if objDraw then
                local name = objDraw.name
                destroyImmediate(objDraw)
                objDraw = nil
                HelperFunc.UnloadSingleLihui(name)
            end
            if drawWrapper2 ~= nil then
                objDraw = newObject(go);
                AudioManager.Play(AudioManager.Play_UI_New_Hero) 
                local canvas = objDraw:AddComponent(TCanvas);
                objDraw:AddComponent(TChangeSortingOrder);
                --canvas.sortingOrder = 99;
                objDraw.name = drawing;
                drawWrapper2:SetWrapTarget(objDraw,true)
                local scale,pos = HeroManager.GetHeroLocationResize(heroId)
                Util.Lua_SetLocalPositionXYZ(objDraw.transform,pos[1],pos[2],0)
                Util.Lua_SetLocalScaleXYZ(objDraw.transform,scale[1],scale[2],0)
                heroLihui:SetNativeObject(drawWrapper2)
                local g = objDraw:GetComponent("SkeletonGraphic")
                g.AnimationState:SetAnimation(0,"idle2",false);
                local idleAniTime = g.AnimationState.Data.SkeletonData:FindAnimation("idle2").Duration;
                if idleTimer == nil then
                    idleTimer = Timer.New(this.delayIdle,idleAniTime,1,false);
                else
                    idleTimer:Reset(this.delayIdle,idleAniTime,1,false);
                end
                idleTimer:Start();

                this.colorObj.a = 0;
                this.curAlpha = 0;
                objDraw:GetComponent("SkeletonGraphic"):SetSkenColor(this.colorObj);

                if this.updateTimer then
                    utimer.remove(this.updateTimer)
                end
            
                this.updateTimer = utimer.timeCall(function()
                    if objDraw then
                        this.curAlpha = this.curAlpha + 0.2
                        this.colorObj.a = this.curAlpha;
                        objDraw:GetComponent("SkeletonGraphic"):SetSkenColor(this.colorObj);
                    end
                end,100,5)
            end
        end);
        procession.url = EnumConst.AtlasPath.ICONAtlas..EnumConst.HeroTypeIcon[heroConfig.f_HeroType];
        local star = logicMgr.HeroManager.starToQuality(this.showHeroStar or heroConfig.f_HeroInitialStar);
        local config = G.dataTable.t_iconframe[tostring(star)]
        local isFrame = config.f_Ornaments ~= ""
        qualityFrame.visible = isFrame
        local atlas = "ui://CharactorUI/"
        if isFrame then
            qualityFrame.url = atlas..config.f_QualityOrnaments
        end
        if config.f_QualityText~= "" then
            qualityIcon.url = atlas..config.f_QualityText
            staegeController.selectedIndex = 1;
        else
            staegeController.selectedIndex = 0;
        end
        local quality = tonumber(config.f_Quality);
        breakStone:setQuality(quality);
        qualityNumIcon.url = atlas..config.f_QualityIcon
        if config.f_Id > 10 then
            staegeController.selectedIndex = 0;
            maxController.selectedIndex = star - 10;
        else
            maxController.selectedIndex = 0;
        end
        -- 播放抽卡语音
        local _controllerIndex = 0
        local _interactionTag = AudioManager.InteractionTagTable[1].Tag
        local _skinId = 0
        local _interactionId = this.heroId.._skinId .. _interactionTag
        local _interactionInfo = G.dataTable["t_interaction"][tostring(_interactionId)]
        if _interactionInfo then
            if not string.IsNilOrEmpty(_interactionInfo.f_LineText) then
                local _introStr = getLanguage(_interactionInfo.f_LineText)
                if not string.IsNilOrEmpty(_introStr) then
                    _controllerIndex = 1
                    this.Txt_ActorLines.text = _introStr
                end
            end
        end
        this.HeroLineTextController:SetSelectedIndex(_controllerIndex)
        AudioManager.PlayInteractionVoice(this.heroId,_skinId,_interactionTag)
    end
    coroutine.wait(1);
    this.spineBooking = 0;
end

function UIDrawAnimation.refresh()
    local skillInfos= logicMgr.SkillManager.getSkillInfosById(currentHeroData.partnerModelId);
    this.refreshSkillIcon(skillInfos[EnumConst.SkillFieldType.Trick],trickGroup,trick);
    this.refreshSkillIcon(skillInfos[EnumConst.SkillFieldType.Speical],specialGroup,special);
    this.refreshSkillIcon(skillInfos[EnumConst.SkillFieldType.SpecialTwo],specialTwoGroup,specialTwo);
    this.refreshSkillIcon(skillInfos[EnumConst.SkillFieldType.Passive],passiveGroup,passive);
    this.refreshSkillIcon(skillInfos[EnumConst.SkillFieldType.skill5],skill5Group,skill5,EnumConst.SkillFieldType.skill5);
    this.ctrlSkillRace.selectedIndex = currentHeroData.faction
    if skillInfos[EnumConst.SkillFieldType.skill5] then
        this.ctrlSkillFifth.selectedIndex = 1
    else
        this.ctrlSkillFifth.selectedIndex = 0
    end
end

function UIDrawAnimation.refreshSkillIcon(skillInfoItem,curGroup,obj,index)
    if skillInfoItem == nil then return end
    local curLv = logicMgr.SkillManager.getSkillLv(skillInfoItem,this.level,currentHeroData.quality); --当前等级
    curGroup["skill"] = skillInfoItem;
    curGroup["level"] = curLv;
    curGroup.ctrlRace = obj:GetController("race")
    curGroup.ctrlFifthSkill = obj:GetController("fifthSkill")
    local iconName = tostring(skillInfoItem["f_SkillIcon"]);
    local icon = obj:GetChild("Mask"):GetChild("Icon")
    icon.url = "ui://SkillAtlas/"..iconName
    if index == EnumConst.SkillFieldType.skill5 then
        local faction = currentHeroData.faction
        if faction == 1 or faction == 2 or faction == 3 then
            curGroup.ctrlRace.selectedIndex = faction
            curGroup.ctrlFifthSkill.selectedIndex = 1
        else
            curGroup.ctrlRace.selectedIndex = 0
        end
    end
end

function UIDrawAnimation.onClickShowTrickSkill()
    if trickGroup["skill"]~=nil then
        showUI(PanelNames.UICharactorInfoHeroSkillDetails,trickGroup["skill"],trickGroup["level"],heroId,{trick,special,specialTwo,passive,skill5});
    end
end

function UIDrawAnimation.onClickShowSpecialSkill()
    if specialGroup["skill"]~=nil then
        showUI(PanelNames.UICharactorInfoHeroSkillDetails,specialGroup["skill"],specialGroup["level"],heroId,{trick,special,specialTwo,passive,skill5});
    end
end

function UIDrawAnimation.onClickShowSpecialTwoSkill()
    if specialTwoGroup["skill"]~=nil then
        showUI(PanelNames.UICharactorInfoHeroSkillDetails,specialTwoGroup["skill"],specialTwoGroup["level"],heroId,{trick,special,specialTwo,passive,skill5});
    end
end

function UIDrawAnimation.onClickShowPassiveSkill()
    if passiveGroup["skill"] then
        showUI(PanelNames.UICharactorInfoHeroSkillDetails,passiveGroup["skill"],passiveGroup["level"],heroId,{trick,special,specialTwo,passive,skill5});
    end
end
function UIDrawAnimation.onClickSkill5()
    if skill5Group["skill"] then
        showUI(PanelNames.UICharactorInfoHeroSkillDetails,skill5Group["skill"],skill5Group["level"],heroId,{trick,special,specialTwo,passive,skill5});
    end
end
function UIDrawAnimation.delayIdle() -- 调用loop的idea
    if not this.isDrawing then
        return;
    end
    local model = objDraw;
    if not HelperFunc.IsNull(model)then
        model:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0,"idle1",true);
    end
end

function UIDrawAnimation.showEffectBook()
    --书本展开过程音效
    AudioManager.TryStopLoopSound()
    AudioManager.Play(4002)
    Util.PlayAction(this.spineBook, "start", false);
    this.fade:Play();
    coroutine.wait(0.5);
    this.spineCardObj.visible = true;
    -- 书本彻底翻开音效
    AudioManager.Play(4004)
    
    if heroId ~= nil then
        -- logError("play>>>>>>>>>ssr")
        AudioManager.SetSwitch("ani_book_summon_type", "Set_Switch_ani_book_summon_SSR")
        Util.PlayAction(this.spineCard, "idle2", false);
    else
        -- logError("play>>>>>>>>>normal")
        AudioManager.SetSwitch("ani_book_summon_type", "Set_Switch_ani_book_summon_normal")
        Util.PlayAction(this.spineCard, "idle", false);
    end
    AudioManager.Play(4005)

    coroutine.wait(3.4);
   
    
    --书本彻底翻开后的召唤阵音效
    
    this.spineBooking = 0;
    this.onClickHero();
end

function UIDrawAnimation.onClickHero()
    if this.spineBooking == 1 then
        return;
    elseif this.spineBooking == 2 then
        this.spineBooking = 1;
        effCoroutine = coroutine.start(this.showEffectBook);
        return;
    elseif this.spineBooking == 3 then
        return;
    end
    this.isDrawing = false;
    if effCoroutine ~= nil then
        coroutine.stop(effCoroutine);
    end
    this.spineBookObj.visible = false;
    this.clearEffect();

    AudioManager.TryStopInteractionVoice()

    if callbackFun ~= nil then
        local ccc = callbackFun;
        callbackFun = nil
        ccc();
    end
end

function UIDrawAnimation.onClickSkip()
    AudioManager.TryStopLoopSound()
    this.spineBooking = 0;
    this.onClickHero();
end

function UIDrawAnimation.onClickHeroSkip()
    closeUI(PanelNames.UIDrawAnimation);
    if callbackSkip ~= nil then
        callbackSkip();
    end
end

return UIDrawAnimation;